$(function(){
	var _id = parseInt($_GET['id']?$_GET['id']: 0);
	/**
	 * @desc 商品信息
	 */
	var global_product = {
			'page': $_GET['page'] ? $_GET['page'] : undefined,//页码
			'pageSize' : $_GET['pageSize'] ? $_GET['pageSize'] : undefined, //页数
			'name': undefined,//商品名称
			'ware': undefined,
	}
	
	
	var global_pro = {
			'page' : $_GET['page'] ? $_GET['page'] : undefined,// 页码
			'pageSize' : $_GET['pageSize'] ? $_GET['pageSize'] : undefined, // 页数
			'cond':[],//查询条件
//			'name' : undefined,// 商品名称
	}
	var global_remove = [];
	var global_count = 1;
	var global_ware;
	var select_units;
	//时间
	dateSelFun($('#salereturn_date'));
	dateSelFun($('#start_time'));
	dateSelFun($('#end_time'));
	
	/**
	 * @desc 单位
	 * 
	 */
	(function(){
		select_units = '<select title="单位" class="form-control unit">'
			+ '<option value="0">单位</option>'
			+ '<option value="6">个</option>'
			+ '<option value="5">支</option>'
			+ '<option value="4">包</option>'
			+ '<option value="2">斤</option>'
			+ '<option value="1">箱</option>' + '</select>';
	})();
	
	if(_id){
		initSaleout();
	}

	/**
	 * @初始化页面
	 */
	function initSaleout() {
		$('#confirm').show();
		$('#save').attr('data-id',parseInt(_id));
		$.get('get-sale-return-info', {'id' : _id}, function(data, status) {
			if(status =='success' && data.Ack =='Success'){
				var H = data.Body.head;
				if(H){
					$('#salereturn_no').val(H.salereturn_no);
					$('#salereturn_date').val(intToLocalDate(H.salereturn_date,1));
					$('#warehouse').val(H.warehouse_id);
					global_ware = H.warehouse_id;
					$('#handle_man').val(H.handle_man);
					$('#remark').val(H.remark);
					$('#create_man').val(H.username).attr('data-id', H.create_man);
					$('#total_amount').val(H.total_amount);//总金额
					$('#customer').val(H.customer_id);
					$('#total_discount').val(H.total_discount);//整单折扣
					$('#discount_amount').val(H.discount_amount);//整单优惠金额
					$('#salereturn_amount').val(H.salereturn_amount);//应收金额
					$('#salereturn_type').val(H.salereturn_type);
					if(+H.confirm_flag){
						$('#save').attr('style','display:none');
						$('#confirm').removeClass().addClass('btn btn-warning btn-sm pull-right').attr('disabled','disabled');
					}
					
					$('#origin_id').val(H.saleout_no).attr('data-id',H.saleout_id);
				}
				var D = data.Body.det;
				if(D){
					$('#stockList').find('tr').remove();
					for(var i in D){
						var tmp_units= '';
						var U = D[i].product_unit;
						tmp_units = '<select class="form-control units"><option value="0" data-rate="0"> </option>';
						for(var j in U){
							tmp_units +='<option value="'+U[j].unit_id+'" data-rate="'+U[j].rate+'">'+U[j].unit_name+'</option>';
						}
						tmp_units +='</select>';
						$('<tr>'
						   +'<td class="text-center" name="ids" data-id="'+D[i].salereturn_det_id+'"  data-saleoutdetid="'+D[i].saleout_det_id+'">'+(+i+1)+'</td>'
						   +'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id="'+D[i].product_id+'"> <i class="fa fa-minus-circle" style="color:red;" ></i></a></td>'
						   +'<td class="text-center" name="name" data-id="'+D[i].product_id+'"><input title="商品名称" readonly type="text" value="'+D[i].product_name+'"'
						   +'class="product_name stock-input50"  style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
						   +'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
						   +'<td class="text-center" name="sn">'+D[i].product_sn+'</td>'
						   +'<td class="text-center" name="quantity"><input type="text" value="'+D[i].quantity+'" class="quantity"></td>'
						   +'<td class="text-center" name="unit" style="width:8%;">'+tmp_units+'</td>'
						   +'<td class="text-center" name="price"><input type="text"  placeholder="0.00" class="price" value="'+D[i].price+'"></td>'
						   +'<td class="text-center" name="discount"><input type="text"  placeholder="0.00" class="discount" value="'+D[i].discount+'"></td>'
						   +'<td class="text-center" name="amount"><input type="text" placeholder="0.00" class="amount" value="'+D[i].amount+'" disabled></td>'
						   +'<td class="text-center" name="unit_relation">'+D[i].unit_content+'</td>'
						   +'<td class="text-center" name="second_unit" style="width:8%;">'+tmp_units+'</td>'
						   +'<td class="text-center" name="second_quantity"><input title="辅助单位数量" type="text" value="'+D[i].second_quantity+'"></td>'
						   +'<td class="text-center" name="second_relation">'+D[i].second_relation+'</td>'
						   +'<td class="text-center" name="base_unit" data-id="'+D[i].base_unit+'">'+D[i].base_name+'</td>'
						   +'<td class="text-center" name="base_quantity"><input title="基本单位数量" type="text" value="'+D[i].base_quantity+'" disabled></td>'
						   +'<td class="text-center" name="base_price"><input title="基本单价" type="text" class="base_price" value="'+D[i].base_price+'" disabled></td>'
						   +'<td class="text-center" name="remark"><input type="text" style="width:100%;" value="'+D[i].remark+'"></td>'
						   +'<td class="text-center"><a href="javascript:void(0)" class="checkStock" data-quantity="'+D[i].product_quantity+'">库存</a></td>'
						   +'</tr>').appendTo('#stockList');
//						$('#stockList').find('tr:last').find('.units').val(D[i].quantity_unit).attr('disabled','disabled');
						$('#stockList').find('tr:last').find('[name="unit"] select').val(D[i].quantity_unit);
						$('#stockList').find('tr:last').find('[name="second_unit"] select').val(D[i].second_unit);
						global_count++;
					}
				}
			}
		});
	};
	
	//更改仓库提示
	$('#warehouse').change(function(){
		var current_ware = $(this).val();
		var tmp_flag = 0;
		if(global_count == 1){
			var pid = $('#stockList').find('.stock-minus-tr').data['id'];
			if(pid != undefined){
				tmp_flag = 1;
			} ;
		}else{
			tmp_flag =1;
		}
		if(tmp_flag){
			layer.confirm('更换仓库，明细将被清除，是否继续?', function(index) {
                var td = $('#stockList').find('tr').find('td:first');
                $.each(td, function(index, item) {
    				var tmp_id = $(item).attr('data-id');
    				if ($.inArray(tmp_id, global_remove) >= 0) {
    					return false;
    				}
    				if(tmp_id){
    					global_remove.push({'salereturn_det_id':tmp_id});
    				}
                })
				$('#stockList').find('tr').remove();
				global_count =1;
				insertOrginHtml();
				global_ware = current_ware;
				
				layer.close(index);
			},function(index){
				$('#warehouse').val(global_ware);
				layer.close(index);
			});
		} else{
			global_ware = current_ware;
		}
	})
	
	
	/**
	 * @desc 选择商品
	 */
	$('#salereturn_detail').on('click','.search-product',function(){
		$('#productName').val('');
		global_product.page = 1;
		global_product.name = undefined;
		getProducts();
		
	})
	//过滤商品
	$('#searchProduct').on('click', function() {
		var _name = trim($('#productName').val());
		global_product.name = _name;
		global_product.page = 1;
		getProducts();
		return;
	})
	
	/**
	 * @desc 查询商品
	 */
	function getProducts(pageInfo){
		if (pageInfo !== undefined) {
			global_product.page = pageInfo.page;
			global_product.pageSize = pageInfo.pageSize;
		}
		global_product.ware = $('#warehouse').val();
		if(global_product.ware == 0){
			alertTips('error','请先选择仓库');
			return false;
		}
		
		$('#product_list').find('tr').remove();
		var index = layer.load();
		 $.ajax({
             url: 'get-products-by-ware',
             type: "GET",
             cache: true,
             data: global_product,
             dataType: "json",
             jsonp: "callback",
             global:false,
             success: function(data){
            	 layer.close(index);
            	 if(data.Ack =='Success'){
	            	 var P = data.Body.list;
						if(P && P.length){
							for(var i in P){
								var tmp_units = ''
								var U = P[i].product_unit;
								tmp_units = '<select class="form-control units"><option value="0" data-rate="0"> </option>';
								for(var j in U){
									tmp_units +='<option value="'+U[j].unit_id+'" data-rate="'+U[j].rate+'">'+U[j].unit_name+'</option>';
								}
								tmp_units +='</select>';
								$('<tr>'
								+'<td class="text-center">'+(+i+1)+'</td>'
								+'<td class="text-center id">'+P[i].product_id+'</td>'
								+'<td class="text-center name">'+P[i].product_name+'</td>'
								+'<td class="text-center sn">'+P[i].product_sn+'</td>'
								+'<td class="text-center quantity">'+P[i].quantity+'</td>'
								+'<td class="text-center unit" data-unit="'+P[i].quantity_unit+'" data-rela="'+P[i].unit_content+'">'+(P[i].unit_name == null ? '':P[i].unit_name)+'</td>'
								+'<td class="text-center"><a href="javascript:void(0)" class="product_select" data-unit="'+encodeURI(tmp_units)+'">选择</a></td>'
								+'</tr>').appendTo('#product_list');
				              
							}
							var pageInfo = data.Body.page;
				            if (typeof pageInfo !== 'undefined'){
				              	refreshPaginationNavBar2($('.paginationNavBar'), pageInfo.page, pageInfo.pageSize, data.Body.count, getProducts);
				            }
						}else {
							$('<tr><td colspan="7" class="text-center">没有数据</td></tr>').appendTo('#product_list');
							refreshPaginationNavBar2($('.paginationNavBar'), 1, 10, 1, getProducts);
						}
					$('#chooseProduct').modal('show');//选择商品窗口
	             } else{
	            	 
	             }
             }
		 })
	}
	
	//添加商品
	$('#product_list').on('click','.product_select',function(){
		var tmp_units = decodeURI($(this).attr('data-unit'));
		var tr =$(this).closest('tr');
		var id = tr.find('.id').text();
		var name = tr.find('.name').text();
		var sn = tr.find('.sn').text();
		var quantity = tr.find('.quantity').text();
		var unit = tr.find('.unit').data('unit');
		if(!+unit){
			alertTips('warning','请在商品管理添加单位');
			return false;
		}
		var unit_name = tr.find('.unit').text();
		var unit_content = tr.find('.unit').attr('data-rela');
		if(global_count == 1){
			var pid = $('#stockList').find('.stock-minus-tr').data['id'];
			if(pid == undefined){
				//刚开始添加数据
				$('#stockList').find('tr:first').remove();
			} ;
		}
//		var units = '<select class="form-control" disabled><option selected value="'+unit+'">'+unit_name+'</option></select>';
		$('<tr>'
		  +'<td class="text-center" name="ids" data-id="">'+global_count+'</td>'
		  +'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id="'+id+'"> <i class="fa fa-minus-circle" style="color:red;" ></i></a></td>'
		  +'<td class="text-center" name="name" data-id="'+id+'"><input title="商品名称" readonly type="text" value="'+name+'"'
		  +'class="product_name stock-input50"  style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
		  +'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
		  +'<td class="text-center" name="sn">'+sn+'</td>'
		  +'<td class="text-center" name="quantity"><input type="text" class="quantity"></td>'
		  +'<td class="text-center" name="unit" style="width:8%;">'+tmp_units+'</td>'
		  +'<td class="text-center" name="price"><input type="text"  placeholder="0.00" class="price"></td>'
		  +'<td class="text-center" name="discount"><input type="text"  placeholder="0.00" class="discount"></td>'
		  +'<td class="text-center" name="amount"><input type="text" placeholder="0.00" class="amount"></td>'
		  +'<td class="text-center" name="unit_relation" style="width:8%;">'+unit_content+'</td>'
		  +'<td class="text-center" name="second_unit" style="width:8%;">'+tmp_units+'</td>'
		  +'<td class="text-center" name="second_quantity"><input title="辅助单位数量" type="text" value="0"></td>'
		  +'<td class="text-center" name="second_relation"></td>'
		  +'<td class="text-center" name="base_unit" data-id="'+unit+'">'+unit_name+'</td>'
		  +'<td class="text-center" name="base_quantity"><input title="基本单位数量" type="text" value="0" disabled></td>'
		  +'<td class="text-center" name="base_price"><input title="基本单价" type="text" class="base_price" value="0.00" disabled></td>'
		  +'<td class="text-center" name="remark"><input type="text" style="width:100%;"></td>'
		  +'<td class="text-center"><a href="javascript:void(0)" class="checkStock" data-quantity="'+quantity+'">库存</a></td>'
		  +'</tr>').appendTo('#stockList');
		$('#stockList').find('tr:last').find('[name="unit"]').find('.units').val(unit);
		global_count++;
	})
	
	//删除数据
	$('#stockList').on('click','.stock-minus-tr',function(){
		var tmp_id = $(this).closest('td').prev('td').attr('data-id');
		if ($.inArray(tmp_id, global_remove) >= 0) {
			return false;
		}
		if(tmp_id){
			global_remove.push({'salereturn_det_id':tmp_id});
		}
		if(global_count == 1){
			return false;
		} else if(global_count == 2){
			//添加一条数据要删除数据 后插入一条空数据
			$('#stockList').find('tr:first').remove();
			global_count--;
			insertOrginHtml();
			SumDiscount();
			return false;
		} else {
			var self = $(this);
			//判断当前要删除的行,下面是否还有记录
            var nextTr = self.parent().parent().next('tr');
            if(nextTr.length){
            	//存在下一行，清空当前行数据
                self.closest('tr').remove();
                // 序号重新排列
                var td = $('#stockList').find('tr').find('td:first');
                $.each(td, function(index, item) {
                    var item = $(item);
                    item.text(index+1);
                })
                global_count--;
                SumDiscount();
                return false;
            } else{
            	//删除的为最后一行
                self.closest('tr').remove();
                global_count--;
                SumDiscount();
                return false;
            }
		}
		
	});
	
	/**
	 * @var 计算增减明细后总金额
	 */
	var SumDiscount = function(){
		var total_amount = 0;
		var total_discount = 0;
		$('#stockList tr').each(function(index,element){
			var _amount = $(element).find('[name="amount"] input').val();
			if(_amount ==''){
				
			} else {
				total_amount += +_amount;
			}
			var _discount = $(element).find('[name="discount"] input').val();
			if(_discount == ''){
				
			}else {
				total_discount += +_discount; 
			}
		})
		var discount_amount = +$('#discount_amount').val();
		$('#total_amount').val(total_amount);
		$('#salereturn_amount').val(total_amount - discount_amount);
		$('#total_discount').val(total_discount);
	};
	
	var insertOrginHtml = function(){
		$('<tr>'
			+'<td class="text-center" name="ids" data-id="">'+global_count+'</td>'
			+'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id=""> <i class="fa fa-minus-circle" style="color:red;" ></i></a></td>'
			+'<td class="text-center" name="name" data-id=""><input title="商品名称" readonly type="text" value=""'
			+'class="product_name stock-input50"  style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
			+'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
			+'<td class="text-center" name="sn"></td>'
			+'<td class="text-center" name="quantity"><input type="text"></td>'
			+'<td class="text-center" name="unit">'+select_units+'</td>'
			+'<td class="text-center" name="price"><input type="text"></td>'
			+'<td class="text-center" name="discount"><input type="text"></td>'
			+'<td class="text-center" name="amount"><input type="text"></td>'
			+'<td class="text-center" name="unit_relation"><input title="单位关系" type="text" value="0.00"></td>'
			+'<td class="text-center" name="second_unit">'+select_units+'</td>'
			+'<td class="text-center" name="second_quantity"><input title="辅助单位数量" type="text" value="0.00"></td>'
			+'<td class="text-center" name="second_relation"></td>'
			+'<td class="text-center" name="base_unit"><input title="基本单位" type="text" value="0.00"></td>'
			+'<td class="text-center" name="base_quantity"><input title="基本单位数量" type="text" value="0.00" disabled></td>'
			+'<td class="text-center" name="base_price"><input title="基本单价" type="text" class="base_price" value="0.00" disabled></td>'
			+'<td class="text-center" name="remark"><input type="text" style="width:100%;"></td>'
			+'</tr>').appendTo('#stockList');
	};
	
	
	//库存提示
	$('#stockList').on('click','.checkStock',function(){
		var _quantity = $(this).attr('data-quantity');
		if(_quantity !=undefined){
			layer.tips('库存: '+ _quantity, $(this), {
				  tips: [4, '#78BA32']
			});
		}
	});
	
	//名称提示
	$('#stockList').on('click','.product_name',function(){
		var name = $(this).val();
		if(name !=undefined){
			layer.tips(name, $(this), {
				  tips: [4, '#78BA32']
			});
		}
	});
	
	//数量验证 计算价格金额
	$('#stockList').on('keyup','.quantity',function(){
		this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
		var _quantity = $(this).val();
		
		var tr = $(this).closest('tr');
		var _unit = tr.find('[name="unit"] select').val();
		var base_unit = tr.find('[name="base_unit"]').attr('data-id');
		var _rate = tr.find('[name="unit"]').find('option:selected').attr('data-rate');
		if(_unit == base_unit){
			tr.find('[name="base_quantity"] input').val(_quantity * _rate);
		} else {
			tr.find('[name="base_quantity"] input').val(_quantity * _rate);
		}
		var second_rate = tr.find('[name="second_unit"]') .find('option:selected').attr('data-rate');
		if(+second_rate){
			var tmp_quantity = _quantity * _rate /second_rate;
			tr.find('[name="second_quantity"] input').val(tmp_quantity);
			var _unit_name = tr.find('[name="unit"]').find('option:selected').text();
			var second_name = tr.find('[name="second_unit"]').find('option:selected').text();
			
			var second_relation = Math.floor(_quantity*_rate/second_rate)+' '+second_name + ' '+(_quantity*_rate%second_rate)+_unit_name;
			tr.find('[name="second_relation"]').text(second_relation);
		}
		
		var _price = tr.find('.price').val();
		if(_price == ''){
			_price = 0
		}
		var _discount = tr.find('.discount').val();
		if(_discount == ''){
			_discount = 0
		}
		var _amount = (_quantity * _price).toFixed(2) - _discount;
		tr.find('.amount').val(_amount);
		if(_quantity){
			tr.find('[name="base_price"] input').val(((parseFloat(_amount)+parseFloat(_discount)) / (_quantity * _rate)).toFixed(2));
		}
		SumAmount();
	});
	
	//单位验证
	$('#stockList').on('change','[name="unit"] select', function(){
		var unit = $(this).val();
		var rate = $(this).find('option:selected').attr('data-rate');
		var  tr = $(this).closest('tr');
		var quantity = tr.find('[name="quantity"] input').val();
		var second_rate = tr.find('[name="second_unit"]') .find('option:selected').attr('data-rate');
		if(+second_rate){
			var tmp_quantity = quantity * rate /second_rate;
			tr.find('[name="second_quantity"] input').val(tmp_quantity);
			var _unit_name = tr.find('[name="unit"]').find('option:selected').text();
			var second_name = tr.find('[name="second_unit"]').find('option:selected').text();
			
			var second_relation = Math.floor(quantity*rate/second_rate)+' '+second_name + ' '+(quantity*rate%second_rate)+_unit_name;
			tr.find('[name="second_relation"]').text(second_relation);
		}
		tr.find('[name="base_quantity"] input').val(quantity * rate);
		var _amount = parseFloat(tr.find('[name="amount"] input').val());
		var _discount = +tr.find('.discount').val();
		if(_discount == ''){
			_discount = 0
		}
		if(quantity){
			tr.find('[name="base_price"] input').val(((parseFloat(_amount)+parseFloat(_discount)) / (quantity * rate)).toFixed(2));
		}
		
		
		
	})
	
	//辅助单位
	$('#stockList').on('change','[name="second_unit"] select',function(){
		var second_unit = $(this).val();
		var  tr = $(this).closest('tr');
		if(+second_unit){
			var second_rate = $(this).find('option:selected').attr('data-rate');
			var quantity = tr.find('[name="quantity"] input').val();
			var rate = tr.find('[name="unit"]') .find('option:selected').attr('data-rate');
			var tmp_quantity = quantity * rate /second_rate;
			tr.find('[name="second_quantity"] input').val(tmp_quantity);
			
			var _unit_name = tr.find('[name="unit"]').find('option:selected').text();
			var second_name = tr.find('[name="second_unit"]').find('option:selected').text();
			
			var second_relation = Math.floor(quantity*rate/second_rate)+' '+second_name + ' '+(quantity*rate%second_rate)+_unit_name;
			tr.find('[name="second_relation"]').text(second_relation);
		} else {
			tr.find('[name="second_quantity"] input').val('');
			tr.find('[name="second_relation"]').text('');
		}
		
	})
	
	//单位验证 计算价格金额
	$("#stockList").on('keyup','.price',function(){
		var _quantity = $(this).closest('tr').find('[name="quantity"] input').val();
		if(_quantity == ''){
			_quantity = 0;
		}
		this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
		var _price = $(this).val();
		var _discount = $(this).closest('tr').find('.discount').val();
		if(_discount == ''){
			_discount = 0
		}
		var _amount = (_quantity * _price).toFixed(2) - _discount;
		$(this).closest('tr').find('.amount').val(_amount);
		if(_quantity){
			var _rate = +$(this).closest('tr').find('[name="unit"]').find('option:selected').attr('data-rate');
			$(this).closest('tr').find('.base_price').val(((parseFloat(_amount)+parseFloat(_discount))/(_quantity * _rate)).toFixed(2));
		}
		SumAmount();
	});
	//金额验证 计算价格金额
	$('#stockList').on('keyup','.amount', function(){
		this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
		
		var tr = $(this).closest('tr');
		var _quantity = +tr.find('.quantity').val();
		var _amount = +$(this).val();
		var discount = +tr.find('.discount').val();
		if(discount == ''){
			discount = 0
		}
		var _price = ((_amount + discount )/ _quantity).toFixed(2);
//		$(this).closest('tr').find('.price').val(_price);
		if(_quantity == ''){
			tr.find('.price').val(0);
		} else {
			var rate = +tr.find('[name="unit"]').find('option:selected').attr('data-rate');
			tr.find('.price').val(_price);
			tr.find('.base_price').val(((parseFloat(_amount)+parseFloat(discount)) /(_quantity * rate)).toFixed(2));
		}
		SumAmount();
	});
	
	$('#stockList').on('keyup','.discount', function(){
		this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
		var _quantity = $(this).closest('tr').find('.quantity').val();
		var _price = $(this).closest('tr').find('.price').val();
		
		var discount = $(this).closest('tr').find('.discount').val();
		var _amount = (_quantity * _price).toFixed(2) - discount;
		
		$(this).closest('tr').find('.amount').val(_amount);
		SumAmount();
		
		//整单折扣金额
		var total_discount = 0;
		$('#stockList tr').find('.discount').each(function(index,element){
			var _discount = $(element).val();
			if(_discount ==''){
				
			} else {
				total_discount += +_discount;
			}
			
		})
		$('#total_discount').val(total_discount);
	});
	
	/**
	 * @var 计算总金额
	 */
	var SumAmount = function(){
		var total_amount = 0;
		$('#stockList tr').find('.amount').each(function(index,element){
			var _amount = $(element).val();
			if(_amount ==''){
				
			} else {
				total_amount += +_amount;
			}
			
		})
		var discount_amount = +$('#discount_amount').val();
		$('#total_amount').val(total_amount);
		$('#salereturn_amount').val(total_amount - discount_amount);
	};
	
	//金额验证 计算价格金额
	$('#discount_amount').on('keyup', function(){
		this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
		
		var discount_amount = +$(this).val();
		var total_amount = +$('#total_amount').val();
		if(total_amount == ''){
			total_amount = 0
		}
		var amount = (total_amount - discount_amount).toFixed(2);
		$('#salereturn_amount').val(amount);
	});
	
	
	/**
	 * @var 保存单据
	 */
	(function() {
		// 保存
		$('#save').on('click', function() {
			//单头
			var head = salereturn_header();
			if(!head){
				return false;
			}
			//明细
			var detail = salereturn_detail();
			if(!detail){
				return false;
			}
			var ii = layer.load();
			$.post('save-sale-return',{'head':head,'det':detail,'remove': global_remove,'id':_id}, function(data,status){
				setTimeout(function(){
					  layer.close(ii);
				}, 1000);
				if(status =='success'){
					if(data.Ack =='Success'){
						alertTips('success','保存成功');
						setTimeout(function() {
// 							window.location.reload();
							if(_id){
								window.location.reload();
							} else {
								window.location.href="list-sale-return";
							}
						}, 1000);
					}
				} else {
					alertShows('error','网络错误');
				}
			})
		});

	})();	

	var salereturn_header = function() {
		var no = $('#salereturn_no').val();
		var salereturn_date = $('#salereturn_date').val();
		if (salereturn_date.length == 0) {
			alertTips('warning', '请输入退货时间');
			return false;
		}
		var customer = $('#customer').val();
		if (!+customer) {
			alertTips('warning', '请选择客户');
			return false;
		}
		var handle_man = $('#handle_man').val();
		if (!+handle_man) {
			alertTips('warning', '请选择经手人员');
			return false;
		}
		
		var warehouse = $('#warehouse').val();
		if (!+warehouse) {
			alertTips('warning', '请选择仓库');
			return false;
		}
		var origin_id = $('#origin_id').attr('data-id');
		if(origin_id == ''){
			origin_id = 0;
		}
		var remark = $('#remark').val();
		var create_man = $('#create_man').attr('data-id');
		var salereturn_head = {
			'salereturn_no' : no,
			'salereturn_date' : salereturn_date,
			'salereturn_type' : $('#salereturn_type').val(),
			'customer_id' : customer,
			'warehouse_id' : warehouse,
			'handle_man' : handle_man,
			'create_man' : create_man,
			'remark' : remark,
			'total_amount':$('#total_amount').val(),
			'salereturn_amount':$('#salereturn_amount').val(),
			'total_discount': $('#total_discount').val(),
			'discount_amount':$('#discount_amount').val(),
			'saleout_id': origin_id,
		};
		return salereturn_head;
	}
	
	//退货单明细
	var salereturn_detail = function(){
		var product_det=[];
		global_det = [];
		var product_info = [];
		var _tr = $('#stockList').find('tr');
		var flag = 1;
		if(_tr.length == 1){
			var pid = _tr.first('tr').find('td[name="name"]').attr('data-id');
			if(pid == ''){
				alertTips('warning','请选择商品');
				return false;
			}
		}
		_tr.each(function(index,element){
			var tr = $(this);
			var quantity = tr.find('[name="quantity"] input').val();
			if(quantity == ''){
				alertTips('warning','请填写数量');
				flag = 0;
				return false;
			}
			// var stock = tr.find('.checkStock').attr('data-quantity');
			// if(!+stock){
			// 	var name = tr.find('[name="name"] input').val();
			// 	alertTips('warning',name+'是0库存，不能出库。');
			// 	flag = 0;
			// 	return false;
			// }
			var line_id = tr.find('[name="ids"]').attr('data-id');
			if(line_id == ''){
				line_id = 0;
			}
			var amount = tr.find('[name="amount"] input').val();
			var price = tr.find('[name="price"] input').val();
			
			var unit = tr.find('[name="unit"] select').val();
			if(!+unit){
				alertTips('warning','单位不能为空');
				flag = 0;
				return false;
			}
			var saleout_det_id = tr.find('[name="ids"]').attr('data-saleoutdetid');
			if(saleout_det_id == undefined || saleout_det_id ==''){
				saleout_det_id = 0;
			}
			
			var second_quantity =  tr.find('[name="second_quantity"] input').val();
			
			product_det = {
				'salereturn_det_id' : line_id,
				'product_id' : tr.find('[name="name"]').attr('data-id'),
				'quantity' :quantity, 
				'quantity_unit' : tr.find('[name="unit"] select').val(),
				'remark' : tr.find('[name="remark"] input').val(),
				'price' : decimal(price,2),
				'amount' : decimal(amount,2),
				'discount' : tr.find('[name="discount"] input').val(),
				'second_unit':tr.find('[name="second_unit"] select').val(),
				'second_quantity':second_quantity,
				'second_relation':tr.find('[name="second_relation"]').text(),
				'base_unit':tr.find('[name="base_unit"]').attr('data-id'),
				'base_quantity':tr.find('[name="base_quantity"] input').val(),
				'base_price' :tr.find('[name="base_price"] input').val(),
				'saleout_det_id': saleout_det_id,
			};
			product_info.push(product_det);
			product_det = [];
		});
		if(!flag){
			product_info = [];
			return false;
		}
		if(product_info.length == 0){
			alertTips('warning','请选择产品！');
			return false;
		}
		
		return product_info;
	}
	
	
	//编辑页面的确认
	$('#confirm').on('click',function(){		
		//检查是否有确认其他入库功能
		$.get('check-confirm-sale-return',function(data,status){
			if(data.Error =='User authentication fails'){
				alertTips('error', '你没有操作权限，如要操作，请向管理员申请');
				return;
			}
		
			layer.confirm('点击确认销售退货单将无法编辑，是否确认?', function(index) {
				$.get('confirm-sale-return',{'id':_id},function(data,status){
					if(status =='success'){
						if(data.Ack =='Success'){
							alertTips('success','确认成功');
							setTimeout(function(){
//								window.location.reload();
							},1000);
						} else if(data.Error =='total quantity is lt return_quantity'){
							alertTips('error','退货数量大于出库数量,请修改！');
							return false;
						}
					} else{
						alertTips('error','网络错误');
					}
				})
				layer.close(index);
			});
		})
	})
	
	
	//调用采购订单
	$('#select-origin').on('click',function(){
//		$('#chooseOrigin').modal('show');
		getSaleOutMent();
	})
	///采购订单明细全选
	$('#checkAll').on('click',function(){
		if($(this).prop('checked')){
			$('.ids').prop('checked',true);
		} else {
			$('.ids').prop('checked',false);
		}
	})
	
	$('#searchProcure').on('click', function(){
		var starTime = $('#start_time').val();
		var endTime = $('#end_time').val();
		if(starTime > endTime){
			alertTips('warning','开始时间不能大于截至时间！');
			return false;
		}
		global_pro.cond ={
			'starTime': starTime,
			'endTime': endTime,
			'cust':$('#cust_id').val(),
//			'warehouse':$('#warehouse').val(),
		};
//		global_pro.cond ={'cust':$('#cust_id').val()}
		global_pro.page = 1;
		global_pro.pageSize= 5;
		getSaleOutMent();
	})
	/**
	 * @desc 获取采购订单列表
	 * @date 2016-12-16
	 */
	function getSaleOutMent(pageInfo)
	{
		if(pageInfo !== undefined){
			global_pro.page = pageInfo.page;
			global_pro.pageSize = pageInfo.pageSize;
		}
		$('#origin_header').find('tr').remove();
		var first_id = 0;
		var ii = layer.load();
		$.ajax({
            url: 'select-sale-out',
            type: "GET",
            cache: true,
            data: global_pro,
            dataType: "json",
            jsonp: "callback",
            global:false,
            success: function(data){
           	 layer.close(ii);
           	 var P = data.Body.list;
					if(P && P.length){
						for(var i in P){
							$('<tr>'
							+'<td class="text-center">'+(+i+1)+'</td>'
							+'<td class="text-center no" data-id="'+P[i].saleout_id+'">'+P[i].saleout_no+'</td>'
							+'<td class="text-center date">'+intToLocalDate(P[i].saleout_date,1)+'</td>'
							+'<td class="text-center vendor">'+P[i].client_name+'</td>'
							+'<td class="text-center amount">'+P[i].saleout_amount+'</td>'
							+'<td class="text-center remark">'+P[i].remark+'</td>'
							+'<td class="text-center"><a href="javascript:void(0)" class="pro_select">选择</a></td>'
							+'</tr>').appendTo('#origin_header');
						}
						first_id = P[0].saleout_id;//记录第一个id
						var pageInfo = data.Body.page;
			            if (typeof pageInfo !== 'undefined'){
			              	refreshPaginationNavBar2($('.paginationNavBar'), pageInfo.page, pageInfo.pageSize, data.Body.count, getSaleOutMent);
			            }
			            
					}else {
						$('<tr><td colspan="7" class="text-center">没有数据</td></tr>').appendTo('#origin_header');
						refreshPaginationNavBar2($('.paginationNavBar'), 1, 10, 1, getSaleOutMent);
					}
					getSaleOutDet(first_id);
					$('#chooseOrigin').modal('show');//选择订单窗口
					
            }
		})
		
	}
	
	/**
	 * @desc 根据采购订单id 查询明细
	 * @author liaojianwen
	 * @date 2016-12-15
	 */
	function getSaleOutDet(fid)
	{
		if(fid){
			$('#origin_det').find('tr').remove();
			$.get('get-sale-out-detail', {'id':fid}, function(data,status){
				if(status =='success'){
					if(data.Ack =='Success'){
						var D = data.Body;
						for(var i in D){
							$('<tr>'
							 +'<td class="text-center"><input type="checkbox" class="ids" data-id="'+D[i].saleout_det_id+'" data-pid="'+D[i].saleout_id+'" checked></td>'
							 +'<td class="text-center">'+D[i].product_id+'</td>'
							 +'<td class="text-center">'+D[i].product_name+'</td>'
							 +'<td class="text-center">'+D[i].product_sn+'</td>'
							 +'<td class="text-center">'+D[i].quantity+'</td>'
							 +'<td class="text-center">'+D[i].unit_name+'</td>'
							 +'<td class="text-center">'+D[i].return_quantity+'</td>'
							 +'<td class="text-center">'+D[i].minus_quantity+'</td>'
							 +'</tr>').appendTo('#origin_det');
						}
					} else {
						alertTips('error','查询明细错误');
					}
				} else {
					alertTips('error','网络错误');
				}
			});
		}
	}
	
	//
	$('#origin_header').on('click','td',function(){
		var _id = $(this).closest('tr').find('.no').attr('data-id');
		getSaleOutDet(_id);
	})
	
	//@todo 冒泡设置
	$('#origin_header').on('click', '.pro_select', function(e) {
		e.stopPropagation();
		var saleOutId = $(this).closest('tr').find('.no').attr('data-id');// saleout_id
		var pid = '';
		var _ids = [];
		$('#origin_det .ids').each(function(i,element){
			if($(this).prop('checked')){
				_ids.push($(this).attr('data-id'));//sell_det_id
			}
			pid = $(this).attr('data-pid');//sell_id
			
		});
		if(saleOutId != pid){
			_ids =[];
			getSaleOutDet(saleOutId);
		}
		if(_ids.length == 0){
			alertTips('warning','请选择退货商品');
			return false;
		}
		//判断采购订单是否已被未确认的入库单占用
		$.get('check-sale-out-by-id',{'id':saleOutId}, function(data,status){
			if(status =='success' && data.Ack =='Success'){
				alertTips('error','已有退货单调用了此出库单，请先去确认退货单');
				return false;
			} else {
				imploadeProcurement(saleOutId,_ids);
			}
		})
//		imploadeProcurement(saleOutId,_ids);
	});
	
	//采购订单数据导入采购入库单
	var imploadeProcurement = function(saleOutId, ids){
		$.get('../sale/implode-sale-out-info', {'id' : saleOutId}, function(data, status) {
			if(status =='success' && data.Ack =='Success'){
				var H = data.Body.head;
				if(H){
//					$('#pur_no').val(H.purchase_no);
					var dt = new Date();
					var NowDay = dt.getFullYear()+'-'+(dt.getMonth()+1)+'-'+dt.getDate();
					$('#customer').val(H.customer_id);
					$('#salereturn_date').val(NowDay);
					$('#origin_id').val(H.saleout_no).attr('data-id',H.saleout_id);
					$('#warehouse').val(H.warehouse_id);
					$('#handle_man').val(H.handle_man);
					$('#remark').val('销售出库单号:'+ H.saleout_no +' 导入');
					$('#save').attr('data-origin',H.saleout_id);
					
//					$('#total_amount').val(H.total_amount);//合计金额
					$('#total_discount').val(H.total_discount);//整单折扣
					$('#discount_amount').val(H.discount_amount);//整单优惠金额
//					$('#salereturn_amount').val(H.saleout_amount);//应收金额
					
				}
				var D = data.Body.det;
				if(D){
					$('#stockList').find('tr').remove();
					var count = 1;
					for(var i in D){
						for(var j in ids){
							if(D[i].saleout_det_id == ids[j]){
								var tmp_units= '';
								var U = D[i].product_unit;
								tmp_units = '<select class="form-control units"><option value="0" data-rate="0"> </option>';
								for(var j in U){
									tmp_units +='<option value="'+U[j].unit_id+'" data-rate="'+U[j].rate+'">'+U[j].unit_name+'</option>';
								}
								tmp_units +='</select>';
//								var amount = (+D[i].quantity * + D[i].price) - +D[i].discount;
								$('<tr>'
								   +'<td class="text-center" name="ids" data-id="" data-saleoutdetid="'+D[i].saleout_det_id+'">'+count+'</td>'
								   +'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id="'+D[i].goods_id+'"> <i class="fa fa-minus-circle" style="color:red;" ></i></a></td>'
								   +'<td class="text-center" name="name" data-id="'+D[i].product_id+'"><input title="商品名称" readonly type="text" value="'+D[i].product_name+'"'
								   +'class="product_name stock-input50"  style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
								   +'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
								   +'<td class="text-center" name="sn">'+D[i].product_sn+'</td>'
								   +'<td class="text-center" name="quantity"><input type="text" value="'+D[i].quantity+'" class="quantity"></td>'
								   +'<td class="text-center" name="unit" style="width:8%;">'+tmp_units+'</td>'
								   +'<td class="text-center" name="price"><input type="text"  placeholder="0.00" class="price" value="'+D[i].price+'"></td>'
								   +'<td class="text-center" name="discount"><input type="text"  placeholder="0.00" class="discount" value="'+D[i].discount+'"></td>'
								   +'<td class="text-center" name="amount"><input type="text" placeholder="0.00" class="amount" value="'+D[i].amount+'"></td>'
								   +'<td class="text-center" name="unit_relation">'+D[i].unit_content+'</td>'
								   +'<td class="text-center" name="second_unit" style="width:8%;">'+tmp_units+'</td>'
								   +'<td class="text-center" name="second_quantity"><input title="辅助单位数量" type="text" value="'+D[i].second_quantity+'"></td>'
								   +'<td class="text-center" name="second_relation">'+D[i].second_relation+'</td>'
								   +'<td class="text-center" name="base_unit" data-id="'+D[i].base_unit+'">'+D[i].base_name+'</td>'
								   +'<td class="text-center" name="base_quantity"><input title="基本单位数量" type="text" value="'+D[i].left_quantity+'" disabled></td>'
								   +'<td class="text-center" name="base_price"><input title="基本单价" type="text" class="base_price" value="'+D[i].base_price+'" disabled></td>'
								   +'<td class="text-center" name="remark"><input type="text" style="width:100%;" value="'+D[i].remark+'"></td>'
//								   +'<td class="text-center" name="rec_quantity"><input type="text" class="rec_quantity" disabled value='+D[i].received_quantity+'></td>'
//								   +'<td class="text-center" name="minus_quantity"><input type="text" class="minus_quantity" disabled value='+D[i].minus_quantity+'></td>'
								   +'<td class="text-center"><a href="javascript:void(0)" class="checkStock" data-quantity="'+D[i].product_quantity+'">库存</a></td>'
								   +'</tr>').appendTo('#stockList');
//								$('#purchaseList').find('tr:last').find('.units').val(D[i].quantity_unit).attr('disabled','disabled');
								$('#stockList').find('tr:last').find('[name="unit"] select').val(D[i].quantity_unit);
								$('#stockList').find('tr:last').find('[name="second_unit"] select').val(D[i].second_unit);
								
//								var _unit = $('#purchaseList').find('tr:last').find('[name="unit"] select').val();
//								var base_unit = $('#purchaseList').find('tr:last').find('[name="base_unit"]').attr('data-id');
//								var _rate = $('#purchaseList').find('tr:last').find('[name="unit"]').find('option:selected').attr('data-rate');
//								
//								var _quantity = +D[i].minus_quantity; 
//								if(_unit == base_unit){
////									$('#purchaseList').find('tr:last').find('[name="base_quantity"] input').val(_quantity);
//								} else {
//									$('#purchaseList').find('tr:last').find('[name="quantity"] input').val(_quantity / _rate);
//									
////									$('#purchaseList').find('tr:last').find('[name="base_quantity"] input').val(_quantity);
//								
//								}
								global_count++;
								count++
							}
						}
					}
					SumAmount();
				}
			}
		});
	};
	
	
})